// 输入：l1 = [2, 4, 3], l2 = [5, 6, 4]
// 输出：[7, 0, 8]
// 解释：342 + 465 = 807.

// 输入：l1 = [9, 9, 9, 9, 9, 9, 9], l2 = [9, 9, 9, 9]
// 输出：[8, 9, 9, 9, 0, 0, 0, 1]

let l1 = [9, 9, 9, 9, 9, 9, 9], l2 = [9, 9, 9, 9]
// var addTwoNumbers = function (l1, l2) {
//     let dummy = new ListNode(0); // 虚拟头节点
//     let current = dummy;
//     let carry = 0;

//     while (l1 !== null || l2 !== null || carry !== 0) {
//         let sum = carry;
//         if (l1 !== null) {
//             sum += l1.val;
//             l1 = l1.next;
//         }
//         if (l2 !== null) {
//             sum += l2.val;
//             l2 = l2.next;
//         }
//         carry = Math.floor(sum / 10);
//         current.next = new ListNode(sum % 10);
//         current = current.next;
//     }

//     return dummy.next;
// };

var addTwoNumbers = function (l1, l2) {
    let res = new ListNode();
    let head = res;
    let carry = 0;

    while (l1 || l2 || carry !== 0) {
        let sum = carry;
        if (l1 !== null) {
            sum += l1.val;
            l1 = l1.next;
        };
        if (l2 !== null) {
            sum += l2.val;
            l2 = l2.next;
        };
        carry = Math.floor(sum / 10);
        res.next = new ListNode(sum % 10);
        res = res.next;
    }
    return head.next;
}
console.log(addTwoNumbers(l1, l2));
